from ConfigParser import SafeConfigParser
from os import sep , listdir, getenv
from os.path import exists, realpath, isdir, isfile

defaults = {"logindialogtitle" : "Connection setup",
            "connectingtitle"  : "Connecting",
            "connectinglabel"  : "Loading...",
            "connectingremotelabel" : "Connecting to remote host...",
            "hostlabel"        : "Host",
            "portlabel"        : "Port",
            "usernamelabel"    : "Username",
            "passwordlabel"    : "Password",
            "remenberpassword" : "Remenber password.",
            "loginerrormessage": "<b>Error, connection coudn't be established.</b>\nCheck input data, server is running ssh and user is authorized to login.",
            "resumelabel"      : "Resume",
            "browseincomingfolderlabel" : "Incoming folder...",
            "newconnectionlabel" : "Connect to other host...",
            "optiondialogtitle": "Preferences",
            "interfacelabel"   : "Interface",
            "connectionlabel"  : "Torrent",
            "showconnectiontimeout" : "Show reconnection timeout on status bar.",
            "connectiontimeout" : "Reconnection timeout",
            "keepalivetimeout"  : "Time between 'keep alive' connections",
            "buttonvisibility" : "Buttonbar display",
            "hiddenbuttons"    : "Hidden",
            "iconbuttons"      : "Icons only",
            "labeledbuttons"   : "Icons and labels",
            "toolbarbuttons"   : "Toolbar",
            "language"         : "Language",
            "requirecrypt"     : "Require encryptation.",
            "enablepex"        : "Enable peer exchange.",
            "enableupnp"       : "Map port via NAT-PMP or UPnP.",
            "incomingfolder"   : "Incoming folder",
            "findincoming"     : "Browse...",
            "portnumber"       : "Port",
            "downloadlimit"    : "Download limit",
            "uploadlimit"      : "Upload limit",
            "optionsettedonnextconnection" : "This options will be applied on next connection.",
            "addtorrentdialog" : ".torrent file selector",
            "bittorentfile"    : "Bittorrent file",
            "removedialog"     : "Removing download",
            "removedialoginfo" : "Are you sure? You will left downloaded data.",
            "concurrencyerror" : "Concurrency error, data won't be refreshed.",
            "transmissiondaemonnotrunning" : "Transmission daemon is't running.",
            "nodataerror"      : "No data.",
            "month"            : "month",
            "months"           : "months",
            "week"             : "week",
            "weeks"            : "weeks",
            "day"              : "day",
            "days"             : "days",
            "hour"             : "hour",
            "hours"            : "hours",
            "minute"           : "minute",
            "minutes"          : "minutes",
            "second"           : "second",
            "seconds"          : "seconds",
            "estimateddtime"   : "Estimated time to finish: ",
            "unknownestimate"  : "Unknown time to finish.",
            "seeding"          : "Seeding.",
            "paused"           : "Paused.",
            "checkingfiles"    : "Checking files.",
            "unknownstate"     : "Unknown state.",
            "torrentname"      : "Filename",
            "torrentsize"      : "Size",
            "torrentspeed"     : "Speed",
            "torrentinfo"      : "Information",
            "selectfolder"     : "Select folder",
            "tdaemonkilling"   : "Stopping transmission-daemon",
            "tsearchbox"       : "Torrent search",
            "disconnected"     : "Disconnected",
            "connecting"       : "Connecting",
            "clientconfig"     : "Client",
            "notimplemented"   : "Not implemented yet",
            "noconfigfile"     : "Unable to find transmission-daemon config file, try to start a download to forcing make it. If problem persist contact develepers.",
            "showsearchbox"    : "Show search box.",
            "alltab"           : "All",
            "pausedtab"        : "Paused",
            "downloadingtab"   : "Downloading",
            "uploadingtab"     : "Uploading",
            "finishedtab"      : "Finished",
            "connectionalivetimeout" : "Checking alive connection timeout",
            "nfiles" : "$n files",
            "nfile" : "$n file",
            "Obn" : "Order by name",
            "Obt" : "Order by time",
            "Obs" : "Order by size",
            "Asc" : "Ascending",
            "Des" : "Descending",
            "zeromeansdisabled" : "0 means disabled.",
            "downloaddownloading"    : "Downloading",
            "downloadprogresswindow" : "Downloads",
            "scpdownloading"         : "Downloading via SSH",
            "downloadcanceled"       : "Aborted by user",
            "downloadinterrupted"    : "Interrupted",
            "downloadfinished"       : "Finished",
            "scpfinished"            : "Finished",
            "downloadfolderselector" : "Destination folder",
            "sshbrowser"             : "Remote browser",
            "bittorrentfile"         : "Bittorrent file",
            "fileinfotitle" : "File information",
            "fileinfoname"  : "Filename",
            "fileinfomime"  : "Mimetype",
            "fileinfodate"  : "Modified",
            "fileinfosize"  : "Size",
            "fileinfousername"  : "Owner's username",
            "fileinfousergroup" : "Owner's group",
            "removeconfirmation" : "Are you sure of removing DEFINITELY this files?",
            "clearstoped" : "Clear stoped",
            "forbiddenfolder" : "Unaccessible content.",
            }

def set_locale(new):
    global locale
    if new == "en_US":
        locale = new
        for i in defaults.keys():
            lang.set("DEFAULT",i,defaults[i])
    else:
        langfile = None
        if new != None and isdir(langfolder):
            for i in listdir(langfolder):
                tmp = i.split()[-1]
                if tmp == new:
                    tmp = langfolder+sep+i
                    if isfile(tmp):
                        langfile = tmp
                        break
        if langfile!=None:
            try:
                lang.read(langfile)
                locale = new
            except:
                print "Not valid language file %s" % langfile

def get_locale():
    return locale

def available_langs():
    toreturn = ["Default (en_US)"]
    if isdir(langfolder):
        for i in listdir(langfolder):
            if isfile(langfolder+sep+i):
                tmp = i.split()
                if len(tmp)==2:
                    tmp = tmp[0] +" (" + tmp[1] + ")"
                else:
                    tmp = tmp[0]
                toreturn.append(tmp)
    return toreturn

def _(message):
    message = str(message)
    if lang.has_option("DEFAULT",message):
        return lang.get("DEFAULT",message).replace("\\n","\n")
    else:
        return message

def defaultize(filename):
    file = open(filename,"w")
    lang.write(file)
    file.close()

def set_langfolder(new):
    global langfolder
    langfolder = new

def get_langfolder():
    return langfolder

langfolder = "lang"
lang = SafeConfigParser(defaults)
locale = getenv("LANG")
if locale!=None:
    set_locale(locale.split(".")[0])
else:
    locale = "en_US"



